<template>
  <div class="orderReport">
    <DFPageList ref="dfPageListRef" :page-options="pageOptions" />
  </div>
</template>

<script lang="ts" setup name="OrderReport">
  import lang from './lang';
  import {
    confirmOrderReport,
    delOrderReport,
    pageOrderReport,
    exportOrderReport,
  } from '@/api/wip/orderReport';
  import { useMixins } from '@/hooks/useMixins';
  import { listMaterial } from '@/api/base/material';
  import { listMachine } from '@/api/base/machine';
  import { listShift } from '@/api/base/shift';
  import { dateFn } from '@/utils/http/axios/ipcIndex';

  const { loadLangFn, t } = useMixins();

  const dfPageListRef: any = ref(null);

  loadLangFn(lang);

  const machineList = ref([]);

  const materialList = ref([]);

  const reportStatusList = ref([
    {
      label: t('orderReport.table.unConfirmed'),
      value: 0,
    },
    {
      label: t('orderReport.table.confirmed'),
      value: 1,
    },
  ]);

  const shiftList = ref([]);

  const userList = ref([]);

  function disablePreviousDate(startDate, endDate) {
    const currentDate = new Date();
    // 如果结束日期晚于当前时间，则禁用
    if (endDate && endDate > currentDate) return true;

    // 如果开始日期晚于当前时间，则禁用
    if (startDate && startDate > currentDate) return true;

    return false; // 其他情况下不禁用
  }

  const reportTime = ref({
    createStartTime: ``,
    createEndTime: ``,
    defaultValue: [],
  });

  const maxVal = ref(10);

  function primaryFn(row) {
    if (row && dfPageListRef && dfPageListRef.value) {
      const { shiftCode, reportUserList, reportNum, id } = row;

      dfPageListRef.value.openModalFn('primary', null, t('orderReport.table.reportConfirm'));

      const obj = shiftList.value.find((item) => item.value === shiftCode);

      if (obj && obj.userList && obj.userList.length)
        userList.value = obj.userList.map((item) => ({ label: item.nickName, value: item.userId }));

      maxVal.value = reportNum;

      nextTick(() => {
        dfPageListRef.value.setFieldsValueFn({
          id,
          reportNum,
          shiftCode,
          userList: reportUserList,
          reportConfirmNum: reportNum,
        });
      });
    }
  }

  const shiftCode = ref(null);

  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          label: 'fastSearch',
          component: 'NInput',
        },
        {
          label: 'status',
          prop: 'reportStatus',
          common: true,
          component: 'NSelect',
          options: reportStatusList,
        },
        {
          label: 'reportTime',
          component: 'NDatePicker',
          defaultValue: null,
          componentProps: {
            clearable: true,
            type: 'datetimerange',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            format: 'yyyy-MM-dd HH:mm:ss',
            defaultTime: ['00:00:00', '23:59:59'],
            isDateDisabled: disablePreviousDate,
            // isTimeDisabled:(time: number) => {
            //   return getTimeDisabled(time,1);
            // },
            onUpdateValue: (_, v: string[]) => {
              console.log(_, v);
              if (v) {
                reportTime.value.createStartTime = v[0];
                reportTime.value.createEndTime = v[1];
              } else {
                reportTime.value.createStartTime = '';
                reportTime.value.createEndTime = '';
              }
            },
          },
        },
        {
          label: 'machineName',
          prop: 'machineCode',
          component: 'NSelect',
          options: machineList,
        },
        {
          label: 'shiftName',
          prop: 'shiftCode',
          component: 'NSelect',
          options: shiftList,
        },
        {
          label: 'materialName',
          prop: 'materialCode',
          component: 'NSelect',
          options: materialList,
        },
      ],
    },
    table: {
      hasSelection: true,
      columns: [
        {
          width: 120,
          label: 'reportCode',
        },
        {
          width: 120,
          label: 'orderCode',
        },
        {
          width: 120,
          label: 'machineName',
        },
        {
          width: 120,
          label: 'materialName',
        },
        {
          width: 120,
          label: 'version',
        },
        {
          width: 120,
          label: 'orderNum',
        },
        {
          width: 120,
          label: 'reportNum',
        },
        {
          width: 120,
          label: 'reportConfirmNum',
        },
        {
          width: 120,
          label: 'goodNum',
        },
        {
          width: 120,
          label: 'badNum',
        },
        {
          width: 120,
          label: 'shiftName',
        },
        {
          width: 120,
          label: 'reportUserList',
          prop: 'reportNickNameList',
        },
        {
          width: 120,
          label: 'reportTime',
          render: (row) => {
            return h('span', {
              innerText: row.reportTime ? dateFn(new Date(row.reportTime)) : '-',
            });
          },
        },
        {
          width: 120,
          label: 'status',
          prop: 'reportStatus',
          common: true,
        },
        {
          width: 120,
          label: 'remark',
          common: true,
        },
      ],
      action: {
        columns: [
          {
            label: 'primary',
            disabled: (row) => row.reportStatus === 1,
            click: (row) => {
              primaryFn(row);
            },
          },
          // {
          //   label: 'delete',
          // },
        ],
      },
      operaColumn: [
        {
          label: 'export',
        },
      ],
      requestFn: pageOrderReport,
      delRequestFn: delOrderReport,
      exportRequestFn: exportOrderReport,
    },
    modalFormDialog: {
      formSchemas: [
        {
          label: 'reportNum',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
          disabled: () => true,
        },
        {
          label: 'reportConfirmNum',
          component: 'NInputNumber',
          required: true,
          requiredRulesType: 'number',
          componentProps: {
            maxlength: 50,
            min: 0,
            max: maxVal,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'badNum',
          component: 'NInputNumber',
          required: true,
          requiredRulesType: 'number',
          componentProps: {
            defaultValue: 0,
            maxlength: 50,
            min: 0,
            max: maxVal,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          field: 'shiftCode',
          component: 'NSelect',
          label: 'shiftName',
          defaultValue: null,
          componentProps: {
            clearable: true,
            options: shiftList,
            onUpdateValue: (val) => {
              if (shiftCode.value !== val) {
                shiftCode.value = val;

                if (val) {
                  const obj = shiftList.value.find((item) => item.value === val);

                  if (obj && obj.userList && obj.userList.length)
                    userList.value = obj.userList.map((item) => ({
                      label: item.nickName,
                      value: item.userId,
                    }));
                } else {
                  userList.value = [];
                }

                dfPageListRef.value.setFieldsValueFn({ userList: [] });
              }
            },
          },
          rules: [{ required: true, message: t('common.formTipMsg.input'), trigger: ['change'] }],
        },
        {
          field: 'userList',
          component: 'NCheckbox',
          label: 'reportUserList',
          defaultValue: [],
          componentProps: {
            clearable: true,
            options: userList,
          },
          rules: [
            {
              required: true,
              type: 'array',
              message: t('common.formTipMsg.input'),
              trigger: ['change'],
            },
          ],
        },
        {
          label: 'remark',
          common: true,
          type: 'textarea',
          span: 3,
          giProps: { span: 4 },
        },
      ],
      submitDataFn: confirmOrderReport,
    },
  };

  async function initDictData() {
    const res = await Promise.all([listShift(), listMachine(), listMaterial()]);

    const [res1, res2, res3] = res;

    shiftList.value =
      res1?.data.map((item) => ({
        label: item.shiftName,
        value: item.shiftCode,
        userList: item.userList,
      })) || [];

    machineList.value =
      res2?.data.map((item) => ({ label: item.machineName, value: item.machineCode })) || [];

    materialList.value =
      res3?.data.map((item) => ({ label: `${item.materialName}`, value: item.materialCode })) || [];
  }

  initDictData();

  // nextTick(() => {
  //   dfPageListRef.value && dfPageListRef.value.openModalFn();
  // });
</script>
